package com.yeyks.mattress.controller;

import com.yeyks.common.ajax.AjaxResponseBody;
import com.yeyks.common.dto.UserInfoDTO;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.utils.*;
import com.yeyks.commonReference.append.sms.SmsService;
import com.yeyks.consumer.dal.domain.UserInfo;
import com.yeyks.consumer.service.UserInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author fuchangshuai
 * @date 2019/3/26 3:12 PM
 */
@Api(tags = "用户接口", description = "用户")
@Slf4j
@RestController("appUserInfoController")
@RequestMapping(value = "/mattress/user")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private SmsService smsService;


    @ApiOperation(value = "获得短信验证用于注册:v1.0.0")
    @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", required = true, dataType = "String")
    @RequestMapping(value = "/getVerifyCode", method = RequestMethod.POST)
    public AjaxResponseBody getVerifyCode(@RequestParam(name = "phone") String phone) {
        checkParamPhone(phone);
        return sendMessage(phone);
    }

    @ApiOperation(value = "用户登陆:v1.0.0", notes = "使用手机号验证码或者手机号密码登陆")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "code", value = "验证码", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "phone", value = "手机号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "密码", dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "sourceType", value = "来源", defaultValue = "iOS", dataType = "String")
    })
    @PostMapping(value = "/login")
    public AjaxResponseBody<Map<String, Object>> loginV2(@RequestParam(name = "code", required = false) String code,
                                                         @RequestParam(name = "phone") String phone,
                                                         @RequestParam(name = "password", required = false) String password,
                                                         @RequestParam(name = "sourceType", defaultValue = "iOS") String sourceType) {
        //非验证码登陆
        if (code == null || code.isEmpty()) {
            checkParamPhonePwd(phone, password);
            //加密密码
            password = AppServerUtil.getEncodePassword(password);
            //用户的话使用手机号密码登陆
            UserInfo userInfo = userInfoService.selectUseInfoPhone(phone);
            if (userInfo == null) {
                throw new ServiceException("该用户不存在");
            }
            if (!password.equals(userInfo.getMd5Password())) {
                throw new ServiceException("密码输入有误");
            }
            return packLoginResult(userInfo);
        }
        checkParamPhone(phone);
        if (smsService.verifySmsForSignup(phone, code)) {
            // 查找用户的所有信息
            UserInfo exist = userInfoService.selectUseInfoPhone(phone);
            if (exist != null) {
                return packLoginResult(exist);
            } else {
                UserInfo userInfo = getUserInfo(sourceType, phone);
                userInfoService.insertReturnId(userInfo);
                if (userInfo.getId() != null) {
                    userInfo.setInviteCode(InvateCode.toSerialCode(userInfo.getId()));
                    int res = userInfoService.updateUserInfo(userInfo);
                    if (res != 1) {
                        log.info("更新邀请码异常");
                    }
                    //给新用户发两张10元优惠券
//                    userCouponService.createNewCoupon(userInfo.getId());
                }
                return packLoginResult(userInfo);
            }
        } else {
            return AjaxResponseBody.failed("验证码无效");
        }
    }

    private AjaxResponseBody sendMessage(String phone) {
        try {
            smsService.sendSmsForSignup(phone);
            return AjaxResponseBody.success(true);
        } catch (ServiceException e) {
            // 其它写入失败
            return AjaxResponseBody.failed(-1, e.getMessage());
        } catch (Throwable e) {
            // 其它写入失败
            return AjaxResponseBody.failed(-1, "fail");
        }
    }

    private UserInfo getUserInfo(String sourceType, String phone) {
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(Utility.randomName());
        userInfo.setPassword(null);
        userInfo.setType(1);
        userInfo.setPhone(phone);
        userInfo.setValid(true);
        userInfo.setStatus(1);
        userInfo.setSourceType(sourceType);
        userInfo.setIsVip(0);
        userInfo.setIsDel(1);
        return userInfo;
    }

    private AjaxResponseBody<Map<String, Object>> packLoginResult(UserInfo userInfo) {
        UserInfoDTO userInfoDTO = ObjectConvertUtil.convertObject(userInfo, UserInfoDTO.class);
        userInfoDTO.setVipStatus(userInfo.getIsVip());
        if (ArgumentsCheckUtil.strIsNull(userInfo.getPassword())) {
            userInfoDTO.setPassword(null);
        } else {
            userInfoDTO.setPassword("yyks2019");
        }
        // 用户ID生成Token
        String token = userInfoService.getTokenByUseId(userInfo.getId());
        // 生成结果
        Map<String, Object> res = new HashMap<>();
        res.put("user_info", userInfoDTO);
        res.put("token", token);
        return AjaxResponseBody.success(res);
    }

    private void checkParamPhone(String phone) {
        if (ArgumentsCheckUtil.isEmpty(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        if (!TextValidator.MOBILE.boolCheck(phone)) {
            throw new ServiceException("手机号格式非法");
        }
    }

    private void checkParamPhonePwd(String phone, String password) {
        if (ArgumentsCheckUtil.isEmpty(phone)) {
            throw new ServiceException("手机号不能为空");
        }
        if (!TextValidator.MOBILE.boolCheck(phone)) {
            throw new ServiceException("手机号格式非法");
        }
        if (ArgumentsCheckUtil.isEmpty(password)) {
            throw new ServiceException("密码输入为空");
        }
        if (password.length() < 6 || password.length() > 16) {
            throw new ServiceException("密码的有效长度为6-16位");
        }
    }
}
